<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Jobs\ExcelTaskController;
use App\Models\Common\Constant;


//spu面料系统
class SelfSpuInfoModel extends BaseModel
{



    //spu图片保存
    public function SaveSpuImgsM($params){
        if(!isset($params['spu_id'])){
            return $this->FailBack('无spuid'); 
        }
        $spu_id = $params['spu_id'];
        $base_spu_id = $params['base_spu_id'];
        $color_id = $params['color_id'];
        $imgs = $params['img'];
        $type = $params['type'];

        $insert['base_spu_id'] = $base_spu_id;
        $insert['color_id'] = $color_id;
        $insert['type'] = $type;

        if(isset($params['id'])){
            $id = $params['id'];
            if(isset($params['status'])){
                $insert['status'] = -1;
            }

            foreach ($imgs as $img) {
                $insert['img'] = $img;
                db::table('self_spu_info_img')->where('id',$id)->update($insert);
            }
        }else{

            foreach ($imgs as $img) {
                $insert['img'] = $img;
                db::table('self_spu_info_img')->insert($insert);
            }
        }
        return $this->SBack([]);        
    }


    public function DelSpuImgsM($params){
        $ids = $params['id'];
        db::table('self_spu_info_img')->whereIn('id',$ids)->delete();
        return $this->SBack([]);  
    }

    public function GetSpuImgsM($params){
        $list = db::table('self_spu_info_img')->where('status',0);
        if(!isset($params['spu_id'])){
            return $this->FailBack('无spuid'); 
        }
        $spu_id = $params['spu_id'];
        // $base_spu_id = $params['base_spu_id'];
        $list = $list->where('spu_id',$spu_id);
        if(isset($params['color_id'])){
            $list = $list->where('color_id',$params['color_id']);
        }
        if(isset($params['type'])){
            $list = $list->where('type',$params['type']);
        }

        $orderby = 'DESC';
        if(isset($params['orderby_id'])){
            if($params['orderby_id']==1){
                $orderby = 'ASC';
            }
        }


        // $totalNum = $list->count();
        $list = $list->orderby('id', $orderby)->get();
        // $new_list = [];
        // foreach ($list as $v) {
        //     # code...
        //     $new_list[$v->type]['type'] = $v->type;
        //     $new_list[$v->type]['imgs'][] = $v->img;
        // }
        // $new_list = array_values($new_list);
        // $data = ['data'=>$new_list,"totalnum"=>$totalNum];
        return $this->SBack($list);     
    }


    //获取basespu下所有库存sku
    public function GetSpuCusM($params){
        $list = db::table('self_custom_sku')->where('base_spu_id',$params['base_spu_id'])->select('id','custom_sku','old_custom_sku');
        if(isset($params['color'])){
            $list = $list->where('color',$params['color']);
        }
        if(isset($params['size'])){
            $list = $list->where('size',$params['size']);
        }
        $list = $list->get();
        return $this->SBack($list);
    }

    //获取basespu下绑定颜色
    public function GetSpuColorM($params){
        $list = db::table('self_spu_color as a')->leftjoin('self_color_size as b','a.color_id','=','b.id')->where('a.base_spu_id',$params['base_spu_id'])->select('b.id','b.name','b.identifying','b.img')->get();
        return $this->SBack($list);
    }

    //获取basespu下绑定尺码
    public function GetSpuSizeM($params){
        $list = db::table('self_spu_size as a')->leftjoin('self_color_size as b','a.size_id','=','b.id')->where('a.base_spu_id',$params['base_spu_id'])->select('b.id','b.name','b.identifying')->get();
        return $this->SBack($list);
    }

    // `id` int NOT NULL AUTO_INCREMENT,
    // `base_spu_id` int DEFAULT '0',
    // `en_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '',
    // `washing_label` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '洗水唛成分',
    // `material_weight` decimal(10,0) DEFAULT NULL COMMENT '材质克重',
    // `scene` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '适用场景',
    // `fabric_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '面料名称',
    // `material_quality` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '材质成分',
    // `positioning` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '人群定位',
    // `seller_point_desc` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '卖点描述',
    // `style` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '款式季节',
    // `sales_season` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '销售旺季',
    // `plant_info` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '工厂信息',
    // `status` int DEFAULT '1',
    // `body_size_table` longtext COLLATE utf8mb4_general_ci COMMENT '适合人体尺寸表',
    // `product_size_table` longtext COLLATE utf8mb4_general_ci COMMENT '产品尺码表',
    // `sample_sheet` longtext COLLATE utf8mb4_general_ci COMMENT '打样版单',
    // `order_ratio_table` longtext COLLATE utf8mb4_general_ci COMMENT '下单配比表',
    // `order_process_table` longtext COLLATE utf8mb4_general_ci COMMENT '理单资料',
   
    //spu信息保存
    public function SaveSpuInfoM($params){
        if(!isset($params['spu_id'])){
            return $this->FailBack('无spuid'); 
        }
        $data['spu_id'] = $params['spu_id'];
        $data['base_spu_id'] = $params['base_spu_id'];

        $base_info = db::table('self_base_spu')->where('id', $data['base_spu_id'])->first();

        //自主研发款验证必填项
        if($base_info->class==1){

//            if(!isset($params['fabric_one'])){
//                return $this->FailBack('面料1必填');
//            }
//            if(!isset($params['washing_label_id'])){
//                return $this->FailBack('洗水唛成分必填');
//            }
//            if(!isset($params['seller_point_desc'])){
//                return $this->FailBack('卖点描述必填');
//            }
//            if(!isset($params['unit_price'])){
//                return $this->FailBack('含税开发单价必填');
//            }
//
//            if(!isset($params['order_num_desc'])){
//                return $this->FailBack('起订量必填');
//            }
        }

        if(isset($params['en_name'])){
            $data['en_name'] = $params['en_name'];
        }

        if(isset($params['fabric_one'])){
            $data['fabric_one'] = $params['fabric_one'];
        }

        if(isset($params['fabric_two'])){
            $data['fabric_two'] = $params['fabric_two'];
        }


        if(isset($params['washing_label_id'])){
            $data['washing_label_id'] = $params['washing_label_id'];
        }


        if(isset($params['washing_label'])){
            $data['washing_label'] = $params['washing_label'];
        }
        if(isset($params['material_weight'])){
            $data['material_weight'] = $params['material_weight'];
        }
        if(isset($params['scene'])){
            $data['scene'] = $params['scene'];
        }
        if(isset($params['fabric_name'])){
            $data['fabric_name'] = $params['fabric_name'];
        }
        if(isset($params['material_quality'])){
            $data['material_quality'] = $params['material_quality'];
        }
        if(isset($params['positioning'])){
            $data['positioning'] = $params['positioning'];
        }
        if(isset($params['seller_point_desc'])){
            $data['seller_point_desc'] = $params['seller_point_desc'];
        }
        if(isset($params['style'])){
            $data['style'] = $params['style'];
        }
        if(isset($params['sales_season'])){
            $data['sales_season'] = $params['sales_season'];
        }
        if(isset($params['product_status'])){
            $data['product_status'] = $params['product_status'];
        }
        if(isset($params['status'])){
            $data['status'] = $params['status'];
        }
        if(isset($params['status'])){
            $data['status'] = $params['status'];
        }
        if(isset($params['unit_price'])){
            $data['unit_price'] = $params['unit_price'];
        }
        if(isset($params['order_num_desc'])){
            $data['order_num_desc'] = $params['order_num_desc'];
        }
        if(isset($params['body_size_table'])){
            $data['body_size_table'] = json_encode($params['body_size_table']);
        }else{
            $data['body_size_table'] = '';
        }
        if(isset($params['product_size_table'])){
            $data['product_size_table'] =  json_encode($params['product_size_table']);
        }else{
             $data['product_size_table'] = '';
        }
        if(isset($params['sample_sheet'])){
            $data['sample_sheet'] =  json_encode($params['sample_sheet']);
        }else{
            $data['sample_sheet'] = '';
        }
        if(isset($params['order_ratio_table'])){
            $data['order_ratio_table'] =  json_encode($params['order_ratio_table']);
        }else{
            $data['order_ratio_table'] = '';
        }
        if(isset($params['order_process_table'])){
            $data['order_process_table'] =  json_encode($params['order_process_table']);
        }else{
            $data['order_process_table'] = '';
        }
        if(isset($params['opinion'])){
            $data['opinion'] =  json_encode($params['opinion']);
        }else{
            $data['opinion'] = '';
        }

        if(isset($params['plant_info'])){
            $data['plant_info'] = $params['plant_info'];
        }
        $spu_repeat = db::table('self_spu_info')->where('spu_id',$data['spu_id'])->first();

        if($spu_repeat){
            $id =  $spu_repeat->id;
            db::table('self_spu_info')->where('id',$id)->update($data);
            // foreach ($imgs as $img) {
            //     $insert['img'] = $img;
            //     db::table('self_spu_info_img')->where('id',$id)->update($insert);
            // }
        }else{
             db::table('self_spu_info')->insert($data);
            // foreach ($imgs as $img) {
            //     $insert['img'] = $img;
            //     db::table('self_spu_info_img')->insert($insert);
            // }
        }


//   `base_spu_id` int DEFAULT '0',
//   `suppliers_id` int DEFAULT '0',
//   `order_num` int DEFAULT '0' COMMENT '起订量',
//   `day` int DEFAULT '0' COMMENT '生产天数',
//   `price` decimal(10,2) DEFAULT NULL COMMENT '单价',
//   `buy_user_id` int DEFAULT '0' COMMENT '采购员',
//   `plant_type` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '工厂性质',
//   `create_user` int DEFAULT NULL COMMENT '创建用户',
//   `create_time` datetime DEFAULT NULL COMMENT '创建时间',
//   `status` int DEFAULT '1' COMMENT '0取消 1正常',

        if(isset($params['attr'])){
            $attrs = $params['attr'];
            db::table('self_spu_info_attr')->where('spu_id',$data['spu_id'])->update(['status'=>0]);
            $i=0;
            foreach ($attrs as $attr_check) {
                if($attr_check['type']==1){
                    $i++;
                }
            }
            if($i>1){
                return $this->FailBack('最多只能选择一个主要工厂');
            }
            foreach ($attrs as $attr) {
                # code...
                // unset($attr['suppliers']);
                // unset($attr['buy_user']);
                $attr_data['status'] = 1; 
                $attr_data['suppliers_id'] = $attr['suppliers_id']; 
                $attr_data['order_num'] = $attr['order_num']??0; 
                $attr_data['day'] = $attr['day']??0; 
                $attr_data['price'] = $attr['price']??0; 
                $attr_data['buy_user_id'] = $attr['buy_user_id']??0; 
                $attr_data['plant_type'] = $attr['plant_type'];  
                $attr_data['type'] = $attr['type'];  
                $is_repeat = db::table('self_spu_info_attr')->where('spu_id',$data['spu_id'])->where('suppliers_id',$attr['suppliers_id'])->first();
                if($is_repeat){
                    $attr_data['create_user'] = $attr['create_user']??0; 
                    $attr_data['create_time'] = date('Y-m-d H:i:s',time());
                    db::table('self_spu_info_attr')->where('id',$is_repeat->id)->update($attr_data);
                }else{
                    $attr_data['spu_id'] = $data['spu_id'];
                    db::table('self_spu_info_attr')->insert($attr_data);
                }
            }
        }

        return $this->SBack([]);        
    }

    //库存sku箱规列表
    public function CustomSkuBoxList($params){

        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 111
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }


        $list = db::table('self_custom_sku_box as a')->leftjoin('suppliers as b','a.suppliers_id','=','b.Id');
        if(isset($params['custom_sku'])){
           $cus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
           $cus_ids = array_column($cus,'id');
           if(!empty($cus_ids)){
            $list = $list->whereIn('a.custom_sku_id',$cus_ids);
           }
        }

        if(isset($params['spu'])){
            $spus = db::table('self_spu')->where('spu','like','%'.$params['spu'].'%')->orwhere('old_spu','like','%'.$params['spu'].'%')->get()->toarray();
            $spu_ids = array_column($spus,'id');
            if(!empty($spu_ids)){
             $list = $list->whereIn('a.spu_id',$spu_ids);
            }
         }


         if(isset($params['suppliers_name'])){
            $list = $list->where('b.name','like','%'.$params['suppliers_name'].'%');
         }

         
         if(isset($params['supplier_no'])){
            $list = $list->where('b.supplier_no','like','%'.$params['supplier_no'].'%');
         }
         $totalNum = $list->count();
         $list = $list->offset($pagenNum)->limit($limit)->select('a.*','b.supplier_no as suppliers_name')->get();
         foreach ($list as $v){
             $v->suppliers_name = !empty($v->suppliers_name) ? $v->suppliers_name : '请维护供应商代号';
         }


         return $this->SBack(['totalnum'=>$totalNum,'data'=>$list]);       

    }

      //库存sku箱号导入
      public function ImportCustomSkuBox($params){
        $is_weight = $params['is_weight']??0;
        $size = ['XS','S','M','L','XL','2XL','3XL','4XL','5XL','6XL'];
        $row1 = array_merge(['no','spu','a','b','c'],$size);
        $row3 =['product_weight','box_weight','box_size','box_bag_size','is_air','suppliers','user'];
        $p['row'] =  array_merge($row1,$row3);

        $p['file'] = $params['file'];
        $p['start'] = 3;
        $data =  $this->CommonExcelImport($p);

   
        $err = [];

        $new_data = [];
        // db::beginTransaction(); 
        foreach ($data as &$v) {
            $spu = $v['spu'];
            $spu_id = $this->GetSpuId($spu);
            $v['spu_id']= $spu_id;
            foreach ($size as $s) {
                # code...
                if($v[$s]>0){
                    $custom_sku_res = db::table('self_custom_sku')->where('spu_id',$spu_id)->where('size',$s)->get();
                    if(!$custom_sku_res->isNotEmpty()){
                        $err[] = $spu.'-'.$s;
                        break;
                    }else{

                        foreach ($custom_sku_res as $custom_skus) {
                            # code...
                            if($is_weight==1){
                                if(($v['product_weight']*$v[$s]+$v['box_weight'])>21.5){
                                    return ['type'=>'fail','msg'=>$spu.'-'.$s.'重量超过21.5kg'];
                                }
                            }
             

       

                            $i['custom_sku_id'] = $custom_skus->id;
                            $i['custom_sku'] = $custom_skus->custom_sku;
                            $i['spu_id'] =$spu_id;
                            $i['spu'] =$custom_skus->spu;
                            $i['size'] =$s;
                            $i['num'] = $v[$s];
                            $i['product_weight'] =$v['product_weight'];
                            $i['box_weight'] =$v['box_weight'];
                            $i['box_size'] =$v['box_size'];
                            if(empty( $i['box_size'])){
                                return ['type'=>'fail','msg'=>$spu.'-'.$s.'无外箱规格'];
                            }
                            try {
                                $box_size = explode('*',$v['box_size']);
                                $i['box_size_length'] =$box_size[0];
                                $i['box_size_wide'] =$box_size[1];
                                $i['box_size_hight'] =$box_size[2];
                            } catch (\Throwable $th) {
                                //throw $th;
                                return ['type'=>'fail','msg'=>$spu.'-'.$s.'无外箱规格格式有误'];
                            }
       



                            $i['box_bag_size'] =$v['box_bag_size'];
                            $i['is_air'] = 0;
                            if($v['is_air']=='是真空'){
                                $i['is_air'] = 1;
                            }
                            $i['suppliers_id'] = 0;
                            
                            $suppliers = db::table('suppliers')->where('supplier_no',$v['suppliers'])->first();
                            if($suppliers){
                                $i['suppliers_id'] =$suppliers->Id;
                            }
                                
                            $i['user_id'] =db::table('users')->where('account',$v['user'])->first()->Id??0;
                            $i['create_time'] =date('Y-m-d H:i:s',time());
    
                            
                            $box = db::table('self_custom_sku_box')->where('custom_sku_id',$i['custom_sku_id'])->where('suppliers_id',$i['suppliers_id'])->where('size',$s)->first();
    
                            if($box){
                                db::table('self_custom_sku_box')->where('id',$box->id)->update($i);
                            }else{
                                db::table('self_custom_sku_box')->insert($i);
                            }
    
                        }
                       
                    }
                }
            }
        }

        $return['data'] = $data;
        $return['err'] = $err;
        // db::commit();
        if($err){
            return ['msg'=>'导入失败'.implode(',',$err).'尺码，不存在库存sku','type'=>'fail'];
        }
      
        return ['msg'=>'导入成功','type'=>'success','data'=>$return];
    }


     //库存sku信息保存
     public function SaveCusInfoM($params){
        $data['custom_sku_id'] = $params['custom_sku_id'];
        if(isset($params['fabric_one'])){
            $data['fabric_one'] = $params['fabric_one'];
        }
        if(isset($params['fabric_two'])){
            $data['fabric_two'] = $params['fabric_two'];
        }
        if(isset($params['washing_label_id'])){
            $data['washing_label_id'] = $params['washing_label_id'];
        }
        if(isset($params['en_name'])){
            $data['en_name'] = $params['en_name'];
        }
        if(isset($params['washing_label'])){
            $data['washing_label'] = $params['washing_label'];
        }
        if(isset($params['material_weight'])){
            $data['material_weight'] = $params['material_weight'];
        }
        if(isset($params['scene'])){
            $data['scene'] = $params['scene'];
        }
        if(isset($params['fabric_name'])){
            $data['fabric_name'] = $params['fabric_name'];
        }
        if(isset($params['material_quality'])){
            $data['material_quality'] = $params['material_quality'];
        }
        if(isset($params['positioning'])){
            $data['positioning'] = $params['positioning'];
        }
        if(isset($params['seller_point_desc'])){
            $data['seller_point_desc'] = $params['seller_point_desc'];
        }
        if(isset($params['style'])){
            $data['style'] = $params['style'];
        }
        if(isset($params['sales_season'])){
            $data['sales_season'] = $params['sales_season'];
        }
        if(isset($params['plant_info'])){
            $data['plant_info'] = $params['plant_info'];
        }
        if(isset($params['status'])){
            $data['status'] = $params['status'];
        }
        if(isset($params['bag_length'])){
            $data['bag_length'] = $params['bag_length'];
        }
        if(isset($params['bag_width'])){
            $data['bag_width'] = $params['bag_width'];
        }
        if(isset($params['bag_height'])){
            $data['bag_height'] = $params['bag_height'];
        }
        if(isset($params['bag_weight'])){
            $data['bag_weight'] = $params['bag_weight'];
        }
        if(isset($params['product_weight'])){
            $data['product_weight'] = $params['product_weight'];
        }
        if(isset($params['product_weight'])){
            $data['product_weight'] = $params['product_weight'];
        }

        if(isset($params['product_width'])){
            $data['product_width'] = $params['product_width'];
        }


        if(isset($params['product_status'])){
            $data['product_status'] = $params['product_status'];
        }
        


        
        $spu_repeat = db::table('self_cus_info')->where('custom_sku_id',$data['custom_sku_id'])->first();

        if($spu_repeat){
            $id =  $spu_repeat->id;
            db::table('self_cus_info')->where('id',$id)->update($data);
            // foreach ($imgs as $img) {
            //     $insert['img'] = $img;
            //     db::table('self_spu_info_img')->where('id',$id)->update($insert);
            // }
        }else{
             db::table('self_cus_info')->insert($data);
            // foreach ($imgs as $img) {
            //     $insert['img'] = $img;
            //     db::table('self_spu_info_img')->insert($insert);
            // }
        }

        if(isset($params['attr'])){
            $attrs = $params['attr'];
          
            $i=0;
            foreach ($attrs as $attr_check) {
                if($attr_check['type']==1){
                    $i++;
                }
            }
            if($i>1){
                return $this->FailBack('最多只能选择一个主要工厂');
            }

            db::table('self_cus_info_attr')->where('custom_sku_id',$data['custom_sku_id'])->update(['status'=>0]);

            foreach ($attrs as $attr) {
                # code...

                $iattr['status'] = 1; 
                $iattr['create_time'] = date('Y-m-d H:i:s',time()); 
                $iattr['suppliers_id'] = $attr['suppliers_id']; 
                $iattr['tax_points'] = $attr['tax_points']??0; 
                $iattr['new_price'] = $attr['new_price']??0; 
                $iattr['bg_price'] = $attr['bg_price']??0; 
                $iattr['price'] = $attr['price']??0; 
                $iattr['type'] = $attr['type']??0; 
                $iattr['create_user'] = $attr['user']??0;
                 
                $is_repeat = db::table('self_cus_info_attr')->where('custom_sku_id',$data['custom_sku_id'])->where('suppliers_id',$attr['suppliers_id'])->first();
                if($is_repeat){
                    db::table('self_cus_info_attr')->where('id',$is_repeat->id)->update($iattr);
                }else{
                    $iattr['custom_sku_id'] = $data['custom_sku_id'];
                    db::table('self_cus_info_attr')->insert($iattr);
                }
            }
        }

        return $this->SBack([]);        
    }



     //批量修改库存sku信息保存
     public function UpdateCusInfoM($params){
        $cus_ids = $params['custom_sku_id'];
        if(isset($params['en_name'])){
            $data['en_name'] = $params['en_name'];
        }
        if(isset($params['washing_label'])){
            $data['washing_label'] = $params['washing_label'];
        }
        if(isset($params['material_weight'])){
            $data['material_weight'] = $params['material_weight'];
        }
        if(isset($params['scene'])){
            $data['scene'] = $params['scene'];
        }
        if(isset($params['fabric_name'])){
            $data['fabric_name'] = $params['fabric_name'];
        }
        if(isset($params['material_quality'])){
            $data['material_quality'] = $params['material_quality'];
        }
        if(isset($params['positioning'])){
            $data['positioning'] = $params['positioning'];
        }
        if(isset($params['seller_point_desc'])){
            $data['seller_point_desc'] = $params['seller_point_desc'];
        }
        if(isset($params['style'])){
            $data['style'] = $params['style'];
        }
        if(isset($params['sales_season'])){
            $data['sales_season'] = $params['sales_season'];
        }
        if(isset($params['plant_info'])){
            $data['plant_info'] = $params['plant_info'];
        }
        if(isset($params['status'])){
            $data['status'] = $params['status'];
        }
        if(isset($params['bag_length'])){
            $data['bag_length'] = $params['bag_length'];
        }
        if(isset($params['bag_width'])){
            $data['bag_width'] = $params['bag_width'];
        }
        if(isset($params['bag_height'])){
            $data['bag_height'] = $params['bag_height'];
        }
        if(isset($params['bag_weight'])){
            $data['bag_weight'] = $params['bag_weight'];
        }
        if(isset($params['product_weight'])){
            $data['product_weight'] = $params['product_weight'];
        }
        if(isset($params['product_weight'])){
            $data['product_weight'] = $params['product_weight'];
        }

        if(isset($params['product_width'])){
            $data['product_width'] = $params['product_width'];
        }


        if(isset($params['product_status'])){
            $data['product_status'] = $params['product_status'];
        }
        


        foreach ($cus_ids as $cus_id) {
            # code...
            $data['custom_sku_id'] = $cus_id;
            $spu_repeat = db::table('self_cus_info')->where('custom_sku_id',$data['custom_sku_id'])->first();

            if($spu_repeat){
                $id =  $spu_repeat->id;
                db::table('self_cus_info')->where('id',$id)->update($data);
                // foreach ($imgs as $img) {
                //     $insert['img'] = $img;
                //     db::table('self_spu_info_img')->where('id',$id)->update($insert);
                // }
            }else{
                 db::table('self_cus_info')->insert($data);
                // foreach ($imgs as $img) {
                //     $insert['img'] = $img;
                //     db::table('self_spu_info_img')->insert($insert);
                // }
            }
    
            if(isset($params['attr'])){
                $attrs = $params['attr'];
                db::table('self_cus_info_attr')->where('custom_sku_id',$data['custom_sku_id'])->update(['status'=>0]);
                foreach ($attrs as $attr) {
                    # code...
    
                    $iattr['status'] = 1; 
                    $iattr['create_time'] = date('Y-m-d H:i:s',time()); 
                    $iattr['suppliers_id'] = $attr['suppliers_id']; 
                    $iattr['tax_points'] = $attr['tax_points']??0; 
                    $iattr['new_price'] = $attr['new_price']??0; 
                    $iattr['bg_price'] = $attr['bg_price']??0; 
                    $iattr['price'] = $attr['price']??0; 
                    $iattr['create_user'] = $attr['user']??0;
                    $iattr['type'] = $attr['type']??0;
                     
                    $is_repeat = db::table('self_cus_info_attr')->where('custom_sku_id',$data['custom_sku_id'])->where('suppliers_id',$attr['suppliers_id'])->first();
                    if($is_repeat){
                        db::table('self_cus_info_attr')->where('id',$is_repeat->id)->update($iattr);
                    }else{
                        $iattr['custom_sku_id'] = $data['custom_sku_id'];
                        db::table('self_cus_info_attr')->insert($iattr);
                    }
                }
            }
    
        }
        
        return $this->SBack([]);        
    }

    //获取spu详情
    public function GetSpuInfoM($params){

        $spu_id = $params['spu_id']??0;
        $spuinfo = db::table('self_spu')->where('id',$spu_id)->first();
        $spu_status = 0;
        if($spuinfo){
            $spu_status = $spuinfo->spu_status;
        }

        $contract_price = $this->GetSpuContractPrice($spu_id);

        $base_spu_id = $params['base_spu_id'];
        $bases = db::table('self_base_spu')->where('id',$base_spu_id)->first();
        $spu = $bases->base_spu;
        if(!empty($bases->old_base_spu)){
            $spu = $bases->old_base_spu;
        }

        $one_cate = $this->GetCategory($bases->one_cate_id)['name'];
        $two_cate = $this->GetCategory($bases->two_cate_id)['name'];
        $three_cate = $this->GetCategory($bases->three_cate_id)['name'];

        $cn_name  = $one_cate.$three_cate;
        $cate = $one_cate.'/'.$two_cate.'/'.$three_cate;

        $info = db::table('self_spu_info')->where('spu_id',$spu_id)->first();

        $seasonal_style = '';
        if($bases->seasonal_style==1){
            $seasonal_style = '夏季款';
        }
        if($bases->seasonal_style==2){
            $seasonal_style = '冬季款';
        }
        if($bases->seasonal_style==3){
            $seasonal_style = '四季款';
        }


        //获取面料1选项
        $fabric_one_label = $this->GetProductCateInfoByBaseSpuId(['type'=>1,'base_spu_id'=>$base_spu_id]);
        //获取面料2选项
        $fabric_two_label = $this->GetProductCateInfoByBaseSpuId(['type'=>2,'base_spu_id'=>$base_spu_id]);
        //获取面料3选项
        $care_label = $this->GetProductCateInfoByBaseSpuId(['type'=>3,'base_spu_id'=>$base_spu_id]);
        $label = ['fabric_one_label'=>$fabric_one_label,'fabric_two_label'=>$fabric_two_label,'care_label'=>$care_label];

        $img  = $this->GetBaseSpuImg($base_spu_id);
        if(!$info){
            $data = ['name'=>$cn_name,'cate'=>$cate,'spu'=>$spu,'addtype'=>1,'img'=>$img,'seasonal_style'=>$seasonal_style,'spu_status'=>$spu_status,'contract_price'=>$contract_price,'spu_status_name'=>Constant::SPU_STATUS[$spu_status]];
           
            return $this->SBack(['data'=>$data,'label'=>$label]);     
        }
        $info->img = $img;
        $info->seasonal_style = $seasonal_style;
        $info->spu = $spu;
        $info->name = $cn_name;
        $info->cate = $cate;
        $info->addtype = 2;

        $info->body_size_table = json_decode($info->body_size_table);
        $info->product_size_table = json_decode($info->product_size_table);
        $info->sample_sheet = json_decode($info->sample_sheet);
        $info->order_ratio_table = json_decode($info->order_ratio_table);
        $info->order_process_table = json_decode($info->order_process_table);
        $info->opinion = json_decode($info->opinion);

        $fabric_one_name = '';
        $fabric_two_name = '';
        $washing_label_name = '';

        $fabric_ones = db::table('product_cate_info')->whereIn('id',[$info->fabric_one,$info->fabric_two,$info->washing_label_id])->get();
        if($fabric_ones){
            foreach ($fabric_ones as $fabric_v) {
                # code...
                if($fabric_v->id==$info->fabric_one){
                    $fabric_one_name = $fabric_v->value;
                }
                if($fabric_v->id==$info->fabric_two){
                    $fabric_two_name = $fabric_v->value;
                }
                if($fabric_v->id==$info->washing_label_id){
                    $washing_label_name = $fabric_v->value;
                }
            }
        }

        $info->fabric_one_name = $fabric_one_name;
        $info->fabric_two_name = $fabric_two_name;
        $info->washing_label_name = $washing_label_name;

        $attr = db::table('self_spu_info_attr')->where('spu_id',$spu_id)->where('status',1)->get();
        foreach ($attr as $v) {
            # code...
            $suppliers = db::table('suppliers')->where('id',$v->suppliers_id)->first();
            $v->suppliers = '';
            if($suppliers){
                $v->suppliers = $suppliers->name;
            }
            $v->buy_user = $this->GetUsers($v->buy_user_id)['account'];
        }

        $info->attr = $attr;

        $info->spu_status = $spu_status;
        $info->spu_status_name =  Constant::SPU_STATUS[$spu_status];
       

        $info->contract_price = $contract_price;

        // //获取面料1选项
        // $info->fabric_one = $fabric_one_label;
        // //获取面料2选项
        // $info->fabric_two = $fabric_two_label;
        // //获取面料3选项
        // $info->care_label = $care_label;

        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                $params['user_id'] = $users->Id ?? 0;
            }else{
                $params['user_id'] = 0;
            }
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['product_contract_price']]);

        $contractSpuMdl = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->where('b.contract_class', '<>', 5)
            ->where('a.spu_id', $spu_id)
            ->orderBy('a.create_time', 'DESC')
            ->first();
//        $contractSpuList = [];
//        foreach ($contractSpuMdl as $cs) {
//            $key = $cs->spu_id;
//            $contractSpuList[$key] = $cs->one_price;
//        }
        $contractOutSpuMdl = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->where('b.contract_class', 5)
            ->where('a.spu_id', $spu_id)
            ->orderBy('a.create_time', 'DESC')
            ->first();
//        $contractOutSpuList = [];
//        foreach ($contractOutSpuMdl as $cs) {
//            $key = $cs->spu_id;
//            $contractOutSpuList[$key] = $cs->one_price;
//        }

        $contractPrice = $contractSpuMdl->one_price ?? 0.00;
        $contractOutPrice = $contractOutSpuMdl->one_price ?? 0.00;
        $salesOrderPrice = $contractPrice * 1.15;
        $outgoingPrice = $contractOutPrice * 1.19;
//        $info->sales_price = '无权查看';
//        $info->outgoing_price = '无权查看';
//        if ($power['show_product_sales_order_price']){
//            $info->sales_price = $this->floorDecimal($salesOrderPrice);
//        }
//        if ($power['show_product_outgoing_price']){
//            $info->outgoing_price = $this->floorDecimal($outgoingPrice);
//        }
        $info->sales_price = $this->floorDecimal($salesOrderPrice);
        $info->outgoing_price = $this->floorDecimal($outgoingPrice);
        $info->contract_price = '无权查看';
        $info->contract_out_price = '无权查看';
        if ($power['product_contract_price']){
            $info->contract_price = $contractPrice;
            $info->contract_out_price = $contractOutPrice;
        }

        return $this->SBack(['data'=>$info,'label'=>$label]);     
    }

    //spu状态
    public function getSpuStatusType(){
       $status = Constant::SPU_STATUS;
       $data = [];
       foreach ($status as $key => $value) {
        # code...
            $one['name'] = $value;
            $one['id'] = $key;
            $data[] = $one;
       }

       return $this->SBack($data);   
    }

    //修改spu状态
    public function UpdateSpuStatus($params){
        $spu_id = $params['spu_id'];
        $spu = db::table('self_spu')->where('id',$spu_id)->first();
        if(!$spu){
            return $this->FailBack('无此spu');
        }
        if($spu->spu_status!=8){
            return $this->FailBack('只有未完成状态的spu才可以修改为已完成');
        }

        db::table('self_spu')->where('id',$spu_id)->update(['spu_status'=>9,'spu_status_time'=>date('Y-m-d H:i:s',time())]);
        return $this->SBack([]);   
    }


    //根据base_spu_id查询面料选项
    public function GetProductCateInfoByBaseSpuId($params){
        $type = $params['type'];
        $data = [];
        $base_spu = db::table('self_base_spu')->where('id',$params['base_spu_id'])->first();
        if($base_spu){
            $product_cate = db::table('product_cate')->whereRaw("find_in_set({$base_spu->three_cate_id},cate_ids)")->where('type',1)->first();
            if($product_cate){
                $data =  db::table('product_cate_info')->where('product_cate_id',$product_cate->id )->where('type',$type)->get();
            }
        }
        return $data;
    }



    //获取cus详情
    public function GetCusInfosM($params){
        $spu_id = $params['spu_id'];
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        
        $cus = db::table('self_custom_sku')->where('spu_id',$spu_id)->select('custom_sku','old_custom_sku','user_id','create_time','id');
        if(isset($params['color'])){
            if(is_array($params['color'])){
                $cus = $cus->whereIn('color',$params['color']);
            }
        }
        

        if(isset($params['size'])){
            if(is_array($params['size'])){
                $cus = $cus->whereIn('size',$params['size']);
            }
        }
        $totalNum =  $cus->count();
        $cus = $cus->offset($page)->limit($limit)->get();

        if($cus){
            foreach ($cus as $v) {
                # code...
                $v->img = $this->GetCustomskuImg($v->custom_sku);
                $v->custom_sku_id = $v->id;
                $v->user = $this->GetUsers($v->user_id)['account'];
                $v->create_time_at = date('Y-m-d H:i:s',$v->create_time);
                $v->send_user = '';
                $v->send_time = '';
                $v->product_user = '';

                $c_data = $this->GetCusInfoM(['custom_sku_id'=>$v->id]);
                if(!$c_data){
                    return $this->FailBack('请先填写spu基础数据');
                }
                $v->data = $c_data;

            }
        }

        return $this->SBack(['data'=>$cus,'totalnum'=>$totalNum]);
   
    }

    //获取cus详情-单
    public function GetCusInfoM($params){



        $custom_sku_id = $params['custom_sku_id'];
  
        $cus = db::table('self_custom_sku')->where('id',$custom_sku_id)->first();

        $info = db::table('self_cus_info')->where('custom_sku_id',$custom_sku_id)->first();
        $attr = db::table('self_cus_info_attr as a')->leftjoin('suppliers as b','a.suppliers_id','=','b.id')->where('a.custom_sku_id',$custom_sku_id)->where('a.status',1)->select('a.*','b.name as suppliers')->get();

        // if(!$info){
        //     $info = db::table('self_spu_info')->where('base_spu_id',$cus->base_spu_id)->first();
        //     if(!$info){
        //         return '';   
        //     }
        // }
        if($info){
            $i_fabric_one_name = '';
            $i_fabric_two_name = '';
            $i_washing_label_name = '';
    
            $i_fabric_ones = db::table('product_cate_info')->whereIn('id',[$info->fabric_one,$info->fabric_two,$info->washing_label_id])->get();
            if($i_fabric_ones){
                foreach ($i_fabric_ones as $i_fabric_v) {
                    # code...
                    if($i_fabric_v->id==$info->fabric_one){
                        $i_fabric_one_name = $i_fabric_v->value;
                    }
                    if($i_fabric_v->id==$info->fabric_two){
                        $i_fabric_two_name = $i_fabric_v->value;
                    }
                    if($i_fabric_v->id==$info->washing_label_id){
                        $i_washing_label_name = $i_fabric_v->value;
                    }
                }
            }
    
            $info->fabric_one_name = $i_fabric_one_name;
            $info->fabric_two_name = $i_fabric_two_name;
            $info->washing_label_name = $i_washing_label_name;
        }
       



        $infos = db::table('self_spu_info')->where('spu_id',$cus->spu_id)->first();
        if(!$infos){
            return false;
        }


        if($infos){
            
            $fabric_one_name = '';
            $fabric_two_name = '';
            $washing_label_name = '';

            $fabric_ones = db::table('product_cate_info')->whereIn('id',[$infos->fabric_one,$infos->fabric_two,$infos->washing_label_id])->get();
            if($fabric_ones){
                foreach ($fabric_ones as $fabric_v) {
                    # code...
                    if($fabric_v->id==$infos->fabric_one){
                        $fabric_one_name = $fabric_v->value;
                    }
                    if($fabric_v->id==$infos->fabric_two){
                        $fabric_two_name = $fabric_v->value;
                    }
                    if($fabric_v->id==$infos->washing_label_id){
                        $washing_label_name = $fabric_v->value;
                    }
                }
            }

            $infos->fabric_one_name = $fabric_one_name;
            $infos->fabric_two_name = $fabric_two_name;
            $infos->washing_label_name = $washing_label_name;

        }

        // var_dump($attr);
        if(empty($attr[0])){
            $attr = db::table('self_spu_info_attr as a')->leftjoin('suppliers as b','a.suppliers_id','=','b.id')->where('a.spu_id',$cus->spu_id)->where('a.status',1)->select('a.*','b.name as suppliers')->get();
            // $attr = db::table('self_spu_info_attr')->where('base_spu_id',$cus->base_spu_id)->where('status',1)->get();
        }

        if(!$info){
            $info = $infos;
            if(!$info){
                return '';   
            }
        }

        //英文名
        if(empty($info->en_name)){
            if(empty($infos->en_name)){
                $infos->en_name = '.';
            }
            $info->en_name = $infos->en_name;
        }

        //洗水唛成分
        if(empty($info->washing_label_id)){
            if(empty($infos->washing_label)){
                $infos->washing_label_id = '';
                $infos->washing_label_name = '';
            }
            $info->washing_label_id = $infos->washing_label_id;
            $info->washing_label_name = $infos->washing_label_name;

        }

        //面料1
        if(empty($info->fabric_one)){
            if(empty($infos->fabric_one)){
                $infos->fabric_one = '';
                $infos->fabric_one_name = '';
            }
            $info->fabric_one = $infos->fabric_one;
            $info->fabric_one_name = $infos->fabric_one_name;

        }

        //面料2
        if(empty($info->fabric_two)){
            if(empty($infos->fabric_two)){
                $infos->fabric_two = '';
                $infos->fabric_two_name = '';
            }
            $info->fabric_two = $infos->fabric_two;
            $info->fabric_two_name = $infos->fabric_two_name;

        }

        //材质克重
        if(empty($info->material_weight)){
            if(empty($infos->material_weight)){
                $infos->material_weight = '';
            }
            $info->material_weight = $infos->material_weight;

        }

        //适用场景
        if(empty($info->scene)){
            $info->scene = $infos->scene;
            if(empty($infos->scene)){
                $infos->scene = '';
            }
        }

        //面料名称
        if(empty($info->fabric_name)){
            if(empty($infos->fabric_name)){
                $infos->fabric_name = '';
            }
            $info->fabric_name = $infos->fabric_name;

        }

        //材质成分
        if(empty($info->material_quality)){
            $info->material_quality = $infos->material_quality;
            if(empty($infos->material_quality)){
                $infos->material_quality = '';
            }
        }

        //人群定位
        if(empty($info->positioning)){
            if(empty($infos->positioning)){
                $infos->positioning = '';
            }
            $info->positioning = $infos->positioning;

        }

        //卖点描述
        if(empty($info->seller_point_desc)){
            if(empty($infos->seller_point_desc)){
                $infos->seller_point_desc = '';
            }
            $info->seller_point_desc = $infos->seller_point_desc;

        }

        //款式季节
        if(empty($info->style)){
            if(empty($infos->style)){
                $infos->style = '';
            }
            $info->style = $infos->style;

        }

        //销售旺季
        if(empty($info->sales_season)){
            if(empty($infos->sales_season)){
                $infos->sales_season = '';
            }
            $info->sales_season = $infos->sales_season;

        }

        //状态
        if(empty($info->status)){
            if(empty($infos->status)){
                $infos->status = '';
            }
            $info->status = $infos->status;

        }

        $info->img = $this->GetCustomskuImg($cus->custom_sku);


        $info->attr = $attr;
        $info->custom_sku_id = $custom_sku_id;
        return $info;   
    }


    //上架平台
    public function SellCusM($params){
        $custom_sku_id = $params['custom_sku_id'];
        $platform_ids = $params['platform_id'];
        $user_id = $params['user_id'];
        foreach ($platform_ids as $platform_id) {
            # code...
            $insert['custom_sku_id'] =  $custom_sku_id;
            $insert['platform_id'] =  $platform_id;
            $insert['user_id'] =  $user_id;
            $insert['create_time'] =  date('Y-m-d H:i:s',time());
            $cus = db::table('self_custom_sku')->where('id',$custom_sku_id)->first();
            $insert['base_spu_id'] =  $cus->base_spu_id;
            $insert['spu_id'] =  $cus->spu_id;
            db::table('self_spu_info_cusbind')->insert($insert);
        }
    
        return $this->SBack([]);
    }


    //删除平台
    public function DelSellCusM($params){
        $ids = $params['id'];
        db::table('self_spu_info_cusbind')->whereIn('id',$ids)->delete();
        return $this->SBack([]);
    }


    //查询平台
    public function GetSellCusM($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $spu_id = $params['spu_id'];
        $list = db::table('self_spu_info_cusbind')->where('spu_id',$spu_id);

        if(isset($params['platform_id'])){
            $list = $list->whereIn('platform_id',$params['platform_id']);
        }

        $totalNum =  $list->count();
        $list = $list->offset($page)->limit($limit)->get();

        foreach ($list as $v) {
            # code...
            $v->user = $this->GetUsers($v->user_id)['account'];
            $cus= db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            if($cus){
                $v->custom_sku = $cus->custom_sku;
                if(!empty($cus->old_custom_sku)){
                    $v->custom_sku = $cus->old_custom_sku;
                }
            }
        }
        return $this->SBack(['data'=>$list,'totalnum'=>$totalNum]);
    }

    public function GetSysLog($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = db::table('sys_log');
        if(isset($params['function'])){
            $list =  $list->where('function','like','%'.$params['function'].'%');
        }
        if(isset($params['name'])){
            $list =  $list->where('name','like','%'.$params['name'].'%');
        }
        if(isset($params['input'])){
            $list =  $list->where('input','like','%'.$params['input'].'%');
        }
        if(isset($params['output'])){
            $list =  $list->where('output','like','%'.$params['output'].'%');
        }
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $list = $list->whereBetween('create_time', [$params['start_time'], $params['end_time']]);
        }
        if(isset($params['user_id'])){
            $list =  $list->where('user_id',$params['user_id']);
        }
        $totalNum =  $list->count();
        $list = $list->offset($page)->limit($limit)->orderby('create_time','desc')->get();
        foreach ($list as $v) {
            $v->input = json_decode($v->input);
            $v->output = json_decode($v->output);
            $v->user = $this->GetUsers($v->user_id)['account'];
            # code...
        }
        return $this->SBack(['data'=>$list,'totalnum'=>$totalNum]);
    }


    //成功返回
    public function SBack($data){
        return['type'=>'success','data'=>$data,'msg'=>'成功'];
    }

    //失败返回
    public function FailBack($msg){
        return['type'=>'fail','data'=>[],'msg'=>$msg];
    }

    public function getSpuPriceList($params)
    {
        if (isset($params['post_type']) && $params['post_type'] == 2){
            $list = db::table('self_custom_sku as a')
                ->leftJoin('self_spu as b', 'a.spu_id', '=', 'b.id')
                ->leftJoin('self_spu_info as c', 'b.base_spu_id', '=', 'c.base_spu_id');

            if (isset($params['spu_id'])){
                $list = $list->where('a.spu_id', $params['spu_id']);
            }

            if (isset($params['color_id'])){
                $list = $list->where('a.color_id', $params['color_id']);
            }

//            $count = $list->count();
//
//            if (isset($params['limit']) || isset($params['page'])){
//                $limit = $params['limit'] ?? 30;
//                $page = $params['page'] ?? 1;
//                $offsetNum = $limit * ($page-1);
//                $list = $list->limit($limit)
//                    ->offset($offsetNum);
//            }

            $list = $list
                ->select(['a.*', 'b.base_spu_id', 'c.unit_price', 'b.spu', 'b.old_spu', 'b.spu_status'])
                ->get();

            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    $params['user_id'] = $users->Id ?? 0;
                }else{
                    $params['user_id'] = 0;
                }
            }
            $controller = new Controller();
            $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['product_contract_price', 'show_product_sales_order_price', 'show_product_outgoing_price']]);

            $contractSpuMdl = db::table('cloudhouse_custom_sku as a')
                ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
                ->select('a.custom_sku_id', 'a.price', db::raw('sum(a.num) as count'))
//                ->where('b.contract_class', '<>', 5)
                ->where('b.contract_status', 2)
                ->groupBy('a.custom_sku_id', 'a.price')
                ->orderBy('count', 'ASC')
                ->get();
            $contractSpuList = [];
            foreach ($contractSpuMdl as $cs) {
                $key = $cs->custom_sku_id;
                $contractSpuList[$key] = $cs->price;
            }
//            $contractOutSpuMdl = db::table('cloudhouse_custom_sku as a')
//                ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
//                ->where('b.contract_class', 5)
//                ->where('b.contract_status', 2)
//                ->orderBy('b.create_time', 'DESC')
//                ->groupBy('a.custom_sku_id')
//                ->get(['a.custom_sku_id', 'a.price']);
//            $contractOutSpuList = [];
//            foreach ($contractOutSpuMdl as $cs) {
//                $key = $cs->custom_sku_id;
//                $contractOutSpuList[$key] = $cs->price;
//            }
            foreach ($list as $v) {
                $key = $v->id;
                $contractPrice = $contractSpuList[$key] ?? 0.00;
//                $contractOutPrice = $contractOutSpuList[$key] ?? 0.00;
                $salesOrderPrice = $contractPrice * 1.15;
//                $outgoingPrice = $contractOutPrice * 1.19;
                $v->spu_status_name = Constant::SPU_STATUS[$v->spu_status] ?? '';
                $v->new_contract_price = '无权查看';
                $v->new_contract_out_price = '无权查看';
                $v->sales_price = '无权查看';
//                $v->outgoing_price = '无权查看';
                if ($power['product_contract_price']) {
                    $v->new_contract_price = $contractPrice;
//                    $v->new_contract_out_price = $contractOutPrice;
                }
                if ($power['show_product_sales_order_price']) {
                    $v->sales_price = $this->floorDecimal($salesOrderPrice);
                }
//                if ($power['show_product_outgoing_price']) {
//                    $v->outgoing_price = $this->floorDecimal($outgoingPrice);
//                }
                $v->color_name_en = $v->color_name.'/'.$v->color;
                $v->img = $this->GetSpuColorImg($v->spu, $v->color);
                $v->unit_price = $v->unit_price ?? 0.00;
            }

            $p['title']='spu价格一览表'.time();
            $title = [
                'custom_sku'  => '新库存SKU',
                'old_custom_sku'  => '旧库存SKU',
                'name' => '库存SKU中文名',
//                'img' => '图片',
                'spu' => '新SPU',
                'old_spu'     => '旧SPU',
                'color_name_en'            => '颜色',
                'spu_status_name'            => 'spu状态',
                'new_contract_price'       => '合同单价',
                'sales_price'    => '结算单价',
                'unit_price'     => '产品开发价',
            ];

            $p['title_list']  = $title;
            $p['data'] =  $list;
            $userId = 1;
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                if($users){
                    $userId = $users->Id;
                }
            }

            $find_user_id = $userId;
            $p['user_id'] = $find_user_id;
            $p['type'] = 'spu价格一览表导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
        }

        $list = db::table('self_spu as a')
            ->leftJoin('self_spu_color as b', 'a.base_spu_id', '=', 'b.base_spu_id')
            ->leftJoin('self_color_size as c', 'b.color_id', '=', 'c.id');
//            ->leftJoin('self_spu_info as d', 'a.base_spu_id', '=', 'd.base_spu_id');

        if (isset($params['spu_id'])){
            $list = $list->where('a.id', $params['spu_id']);
        }

        if (isset($params['color_id'])){
            $list = $list->where('c.id', $params['color_id']);
        }

        $count = $list->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }

        $list = $list
            ->select(['a.*', 'b.img', 'c.identifying', 'c.name as color_name'])
            ->get();

        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                $params['user_id'] = $users->Id ?? 0;
            }else{
                $params['user_id'] = 0;
            }
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['product_contract_price', 'show_product_sales_order_price', 'show_product_outgoing_price']]);

        $contractSpuMdl = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
//            ->where('b.contract_class', '<>', 5)
            ->where('b.contract_status', 2)
            ->select('a.spu_id', 'a.color_identifying', 'a.one_price', db::raw('sum(a.count) as count'))
            ->groupBy('a.spu_id', 'a.color_identifying', 'a.price')
            ->orderBy('count', 'ASC')
            ->get();
        $contractSpuList = [];
        foreach ($contractSpuMdl as $cs) {
            $key = $cs->spu_id.'-'.$cs->color_identifying;
            $contractSpuList[$key] = $cs->one_price;
        }
//        $contractOutSpuMdl = db::table('cloudhouse_contract as a')
//            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
//            ->where('b.contract_class', 5)
//            ->where('b.contract_status', 2)
//            ->orderBy('a.create_time', 'DESC')
//            ->groupBy('a.spu_id', 'a.color_identifying')
//            ->get(['a.spu_id', 'a.color_identifying', 'a.one_price']);
//        $contractOutSpuList = [];
//        foreach ($contractOutSpuMdl as $cs) {
//            $key = $cs->spu_id.'-'.$cs->color_identifying;
//            $contractOutSpuList[$key] = $cs->one_price;
//        }

        $spuInfoMdl = db::table('self_spu_info')
            ->get()
            ->keyBy('spu_id');
        foreach ($list as $v) {
            $key = $v->id.'-'.$v->identifying;
            $v->unit_price = $spuInfoMdl[$v->id]->unit_price ?? 0.00;
            $contractPrice = $contractSpuList[$key] ?? 0.00;
//            $contractOutPrice = $contractOutSpuList[$key] ?? 0.00;
            $salesOrderPrice = $contractPrice * 1.15;
//            $outgoingPrice = $contractOutPrice * 1.19;
            $v->spu_status_name = Constant::SPU_STATUS[$v->spu_status] ?? '';
            $v->new_contract_price = '无权查看';
            $v->new_contract_out_price = '无权查看';
            $v->sales_price = '无权查看';
//            $v->outgoing_price = '无权查看';
            if ($power['product_contract_price']){
                $v->new_contract_price = $contractPrice;
//                $v->new_contract_out_price = $contractOutPrice;
            }
            if ($power['show_product_sales_order_price']){
                $v->sales_price = $this->floorDecimal($salesOrderPrice);
            }
//            if ($power['show_product_outgoing_price']){
//                $v->outgoing_price = $this->floorDecimal($outgoingPrice);
//            }
        }

//        if (isset($params['post_type']) && $params['post_type'] == 2){
//            $p['title']='spu价格一览表'.time();
//            $title = [
////                'custom_sku'  => '新库存SKU',
////                'old_custom_sku'  => '旧库存SKU',
//                'spu'  => '新库存SKU',
////                'name' => '库存SKU中文名',
////                'img' => '图片',
//                'spu' => '新SPU',
//                'old_spu'     => '旧SPU',
//                'color_name'            => '颜色',
////                'spu_status_name'            => 'spu状态',
//                'new_contract_price'       => '合同单价',
//                'sales_price'    => '结算单价',
////                'new_contract_out_price'      => '最新外发合同单价',
////                'outgoing_price'     => '最新外发成品结算单价',
//                'unit_price'     => '产品开发价',
//            ];
//
//            $p['title_list']  = $title;
//            $p['data'] =  $list;
//            $userId = 1;
//            if (isset($params['token']) && !empty($params['token'])){
//                $users = db::table('users')->where('token',$params['token'])->first();
//                if($users){
//                    $userId = $users->Id;
//                }
//            }
//
//            $find_user_id = $userId;
//            $p['user_id'] = $find_user_id;
//            $p['type'] = 'spu价格一览表导出';
//
//            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
//            try {
//                $job::runJob($p);
//            } catch(\Exception $e){
//                return ['type' => 'fail', 'msg' => '加入队列失败'];
//            }
//        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }
}